package com.example.play.view

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.Gravity.BOTTOM
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ExpandableListView
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.base.app.RouterPath
import com.example.common.entity.CommendEntity
import com.example.common.entity.MovieVideoEntity
import com.example.common.entity.SimpleVideoEntity
import com.example.common.event.CustomEvent
import com.example.common.mvi.BaseMviActivity
import com.example.image.GlideUtils
import com.example.play.R
import com.example.play.adapter.MovieVideoListAdapter
import com.example.play.adapter.SimpleVideoListAdapter
import com.example.play.adapter.SimpleVideoListAdapter.ItemClickListener
import com.example.play.adapter.VideoCommentListAdapter
import com.example.play.databinding.ActivityPlayBinding
import com.example.play.entity.AuthorEntity
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat

@Route(path = RouterPath.PATH_PLAY_PAGE)
@AndroidEntryPoint
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {
    @Autowired
    @JvmField var videoPath:String=""
    @Autowired
    @JvmField var userId:String=""
    @Autowired
    @JvmField var channelId:String=""
    @Autowired
    @JvmField var typeId:Int=0
    @Autowired
    @JvmField var itemId:String=""
    @Autowired
    @JvmField var moduleType:Int=0//默认从首页进入

    var videoTypeId:Int=-1//默认从首页进入

    private lateinit var mDanmuContext: DanmakuContext

    private var pageIndex=1
    private var pageSize=10

    private lateinit var simpleVideoListAdapter: SimpleVideoListAdapter
    private lateinit var movieVideoListAdapter: MovieVideoListAdapter

    private val simpleVideoEntity= mutableListOf<SimpleVideoEntity>()
    private val movieVideoEntity= mutableListOf<MovieVideoEntity>()
    private val mViewModel: PlayViewModel by viewModels ()

    var popupWindow: PopupWindow? = null
    private val commentList = mutableListOf<CommendEntity>()
    private lateinit var commentAdapter: VideoCommentListAdapter

    override fun getLayoutId(): Int = R.layout.activity_play

    override fun initViews() {
        //方式1
       // ARouter.getInstance().inject(this)
        //方式2
        intent.extras?.apply {
            videoPath = getString("videoPath").toString()
            userId = getString("userId").toString()
            channelId = getString("channelId").toString()
            itemId = getString("itemId").toString()
            typeId = getInt("typeId")
            moduleType=getInt("moduleType")
        }
        commentAdapter=VideoCommentListAdapter(commentList)
        //播放GSY播放视频
        mDataBinding.videoPlayer?.apply {
            setUp(videoPath, false, "")
            backButton.visibility=View.GONE
            isLooping=true
            //全屏显示
            fullscreenButton.setOnClickListener {
                startWindowFullscreen(this.context,false,true)
            }
        }

        //点击评论
        mDataBinding.llComment.setOnClickListener {
            showPopupWindow(it)
        }

        //点击事件
        mDataBinding.tvDanmu.setOnClickListener {
            mDataBinding.llDanmuLayout.visibility=View.VISIBLE
        }

        //发送弹幕按钮点击事件
        mDataBinding.ivDanmuSend.setOnClickListener {
            //校验弹幕内容
            var danmuContent=mDataBinding.etDanmuInput.editableText.toString().trim()
            if(!danmuContent.isNullOrEmpty()){
                sendVideoDanmu(danmuContent)
            }
        }
        //初始化弹幕
        initVideoDanmu()

        simpleVideoListAdapter=SimpleVideoListAdapter(simpleVideoEntity).apply {
            setOnItemClickListener(object : ItemClickListener {
                override fun onItemChildClick(v: View, position: Int, entity: SimpleVideoEntity) {
                    //使用EventBus给外部Activity发送事件（方案一）
                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,0))
                    //使用LiveDataBus发送事件（方案二）
                }
            })
        }
        movieVideoListAdapter=MovieVideoListAdapter(movieVideoEntity).apply {
            setOnItemClickListener(object : MovieVideoListAdapter.ItemClickListener {
                override fun onItemChildClick(v: View, position: Int, entity: MovieVideoEntity) {
                    //使用EventBus给外部Activity发送事件（方案一）
                    EventBus.getDefault().post(CustomEvent("PlayActivity",entity,1))
                    //使用LiveDataBus发送事件（方案二）
                }

            })
        }
        mDataBinding.rvUserVideo.apply {
            layoutManager= LinearLayoutManager(this@PlayActivity, LinearLayoutManager.VERTICAL,false)
            if (moduleType == 0){
                adapter = simpleVideoListAdapter
            }else{
                adapter = movieVideoListAdapter
            }
        }
    }
    //评论弹窗
    private fun showPopupWindow(it: View?) {
        val inflater = LayoutInflater.from(this)
        val popupView = inflater.inflate(R.layout.comment_list_layout, null)
        val width = ViewGroup.LayoutParams.MATCH_PARENT
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow = PopupWindow(popupView, width, height).apply {
            // 设置背景，这是点击外部关闭弹窗的必要条件
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            // 设置是否可点击
            isFocusable = true
            // 设置点击外部是否关闭
            isOutsideTouchable = true
            // 设置动画效果
            animationStyle = R.style.BottomSheetDialog
        }
        popupView.findViewById<ExpandableListView>(R.id.expand_list).setAdapter(commentAdapter)
        popupView.findViewById<ImageView>(R.id.iv_commend_send).setOnClickListener {
            var et_commend_input=popupView.findViewById<EditText>(R.id.et_commend_input)
            if (et_commend_input.text.toString().trim().isEmpty()){
                ToastUtils.showLong("请输入评论内容")
                return@setOnClickListener
            }else{
                var comment= CommendEntity(
                    agreenum = 270,
                    content = et_commend_input.text.toString().trim(),
                    createtime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()),
                    datatype = 0,
                    id = 0,
                    itemid = itemId.toLong(),
                    nickname = "视频号007",
                    replyList = mutableListOf(),
                    replytotal = 10,
                    userid = 0,
                    userlogo = "https://img1.baidu.com/it/u=2306417155,1148748420&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                )
                lifecycleScope.launch {
                    mViewModel.channel.send(PlayViewIntent.PublishComment(comment))
                }
                et_commend_input.text.clear()
            }
        }
        popupWindow?.showAtLocation(it,BOTTOM, 0, 0)
    }

    override fun handEvent(event: CustomEvent) {
        when(event.type){
            0-> {
               val simpleVideo = event.data as SimpleVideoEntity
                mDataBinding.videoPlayer.apply {
                    setUp(simpleVideo.videopath,true,"")
                    startPlayLogic()
                }
            }
            1-> {
                val movieVideo = event.data as MovieVideoEntity
                mDataBinding.videoPlayer.apply {
                    setUp(movieVideo.videopath,true,"")
                    startPlayLogic()
                }
            }
        }
    }
    private fun initVideoDanmu() {
        //创建
       mDanmuContext= DanmakuContext.create()
        //准备弹幕
        mDataBinding.danmuView.apply {
            //准备
            prepare(object :BaseDanmakuParser(){
                override fun parse(): IDanmakus {
                    return Danmakus()
                }

            },mDanmuContext)
            //设置回调
            setCallback(object :DrawHandler.Callback{
                override fun prepared() {

                }

                override fun updateTimer(timer: DanmakuTimer?) {

                }

                override fun danmakuShown(danmaku: BaseDanmaku?) {

                }

                override fun drawingFinished() {

                }
            })
        }
    }

    /**
     * 发送弹幕
     */
    private fun sendVideoDanmu(danmuContent: String) {
        mDataBinding.danmuView.clear()
        //封装弹幕实体
        var danmuEntity =mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text=danmuContent
            textSize=30f
            textColor= Color.YELLOW
            padding=10
            time=500
            borderColor=Color.RED
        }
        mDataBinding.danmuView.apply {
            addDanmaku(danmuEntity)
            start()
        }

        //清理一下输入框
        mDataBinding.etDanmuInput.setText("")
        mDataBinding.llDanmuLayout.visibility=View.GONE
    }

    override fun onResume() {
        super.onResume()
        mDataBinding?.videoPlayer?.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mDataBinding?.videoPlayer?.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataBinding?.videoPlayer?.release()
        popupWindow?.dismiss()
    }
    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        //获取作者信息
        mViewModel.channel.send(PlayViewIntent.LoadAuthorById(userId))
        //加载视频列表
        when (moduleType){
            0->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoByChannelId(channelId,pageIndex,pageSize))
                }
            }
            1->{
                if (videoTypeId==-1){
                    mViewModel.channel.send(PlayViewIntent.LoadRecommendMutilVideo(pageIndex,pageSize))
                }else{
                    mViewModel.channel.send(PlayViewIntent.LoadMutilVideoByTypeId(videoTypeId,pageIndex,pageSize))
                }
            }
        }
        mViewModel.channel.send(PlayViewIntent.LoadVideoCommends(moduleType,itemId))
    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collectLatest {
            when(it){
                is PlayUiState.LoadAuthorByIdSuccess-> updateAuthorById(it.list)
                is PlayUiState.LoadRecommendSimpleVideoSuccess-> updateRecommendSimpleVideo(it.list)
                is PlayUiState.LoadRecommendMutilVideoSuccess-> updateRecommendMutilVideo(it.list)
                is PlayUiState.LoadVideoCommendsSuccess -> showVideoCommendList(it.list)
                else->{}
            }
        }
    }

    private fun showVideoCommendList(list: List<CommendEntity>) {
        commentList.clear()
        commentList.addAll(list)
        commentAdapter.notifyDataSetChanged()
    }

    private fun updateAuthorById(entity: AuthorEntity) {
        GlideUtils.loadCircleImage(this,entity.avatar_url,mDataBinding.ivUserIcon)
        mDataBinding.apply {
            tvUserName.text=entity.name
            tvUserDesc.text=entity.author_desc
            tvLikeCount.text=entity.followerscount
            tvSendTime.text=entity.ctime
        }
    }
    private fun updateRecommendSimpleVideo(list: List<SimpleVideoEntity>) {
        if (pageIndex ==1){
            simpleVideoEntity.clear()
        }
        simpleVideoEntity.addAll(list)
        simpleVideoListAdapter.notifyDataSetChanged()
    }

    private fun updateRecommendMutilVideo(list: List<MovieVideoEntity>) {
        if (pageIndex ==1){
            movieVideoEntity.clear()
        }
        movieVideoEntity.addAll(list)
        movieVideoListAdapter.notifyDataSetChanged()
    }
}